// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    manager = new QNetworkAccessManager(this); // 新建QNetworkAccessManager对象

    // 修正信号槽连接，使按钮与其对应的功能匹配
    connect(ui->p2Button, &QPushButton::clicked, this, &MainWindow::pushButton1_clicked);
    connect(ui->p1Button, &QPushButton::clicked, this, &MainWindow::pushButton2_clicked);
    // page1 zip packer
    connect(ui->cleanButton, &QPushButton::clicked, this, &MainWindow::clean_all_pageOneInput);
    connect(ui->cleanButton, &QPushButton::clicked, this, &MainWindow::clean_all_pageOneInput);
    // page 3 sse demo
    connect(ui->startSseButton, &QPushButton::clicked, this, &MainWindow::start_sse_demo);
    connect(ui->stopSseButton, &QPushButton::clicked, this, &MainWindow::stop_sse_demo);
    connect(ui->p3CleanTextBrowserButton, &QPushButton::clicked, this, &MainWindow::clean_p3_browser);
    connect(ui->getRequestTestBtn, &QPushButton::clicked, this, &MainWindow::get_weather);
    // weather api
    connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); // 关联信号和槽
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::pushButton1_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page);
}

void MainWindow::pushButton2_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_2);
}

void MainWindow::clean_all_pageOneInput()
{
    ui->lineEdit->clear();
    ui->fileListTextEdit->clear();
}

void MainWindow::start_sse_demo()
{
    ui->sseStatusLabel->setText("Start!");

    ui->sseTextBrowser->move(0, 0);
    ui->sseTextBrowser->setHtml("<h1>Hello, 20YC编程社区！</h1><p>这是一段 <b>粗体</b> 和 <i>斜体</i> 文本.</p><p><a href=\"https://www.baidu.com\">请点击这里</a> 欢迎关注我们公众号【20YC编程】哦。</p>");
}

void MainWindow::stop_sse_demo()
{
    ui->sseStatusLabel->setText("Stop!");
    ui->sseTextBrowser->append("<p>Stop!</p>");
}

void MainWindow::clean_p3_browser()
{
    ui->sseTextBrowser->clear();
}

void MainWindow::get_weather()
{
    // 创建网络请求
    QNetworkRequest request;

    // 设置请求的URL
    QString url = "https://v2.xxapi.cn/api/weather?city=深圳";
    request.setUrl(QUrl(url));

    // 设置User-Agent头
    request.setHeader(QNetworkRequest::UserAgentHeader, "QT FTP Demo Widget");

    // 发送GET请求
    manager->get(request);
}

// 信号槽接收网络响应，处理接收到的数据
void MainWindow::replyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        // 读取返回的数据
        QByteArray data = reply->readAll();

        ui->sseTextBrowser->append(QString::fromUtf8(data));
    }
    else
    {
        // 处理错误情况
        ui->sseTextBrowser->append("Error: " + reply->errorString());
    }

    // 清理reply对象
    reply->deleteLater();
}
